<?php

namespace App\Http\Controllers;

use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Services\H5Service;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Contracts\Foundation\Application;

class WxOauthController extends Controller
{
    public function oauth(Request $request)
    {
        // 在控制器中添加调试代码
        try {
            $config = config('wechat.official_account.default');
            $app    = Factory::officialAccount($config);

            // 获取前端传递的redirect_url参数，授权后跳转回去
            $redirectUrl = $request->get('url');

            //获取渠道参数
            $channel     = H5Service::getChannel($request->all());

            $realRedirectUrl = config('wechat.official_account.default.oauth.callback') . '?ch=' . $channel . '&url=' . $redirectUrl;

            return $app->oauth->scopes(['snsapi_base'])->redirect($realRedirectUrl);
        } catch (\Exception $e) {
            // 记录完整错误信息
            Log::error('微信授权失败: ' . $e->getMessage(), [
                'trace'   => $e->getTraceAsString(),
                'request' => request()->all(),
            ]);
            throw $e;
        }
    }

    /**
     * 回调调用.
     *
     * @param Request $request
     *
     * @return Application|RedirectResponse|Redirector
     */
    public function oauthCallback(Request $request)
    {
        $config     = config('wechat.official_account.default');
        $app        = Factory::officialAccount($config);
        $wechatUser = $app->oauth->user();

        // 获取openid
        $openid = $wechatUser->getId();

        //获取渠道参数
        $channel = H5Service::getChannel($request->all());

        //生成用户cookie对应的key
        $userCookieKey = 'user_openid' . ($channel ? '_' . $channel : '');

        // 获取最初要跳转的目标地址
        $redirectUrl = urldecode($request->get('url'));
        Cookie::queue(
            Cookie::make($userCookieKey, $openid, 60 * 24 * 7, '/', 'ithook.cn', false, false)
        );
        sleep(1);

        return redirect($redirectUrl);
    }
}
